<?php
namespace Admin\Controller;
use Think\Controller;
class PublicController extends Controller {
	//显示登陆界面
    public function index(){
    		$this->display();
	    }
	//判断登陆
	public function login(){
		if (!IS_POST) $this->error('你访问的页面不存在',U(MODULE_NAME.'/'.CONTROLLER_NAME.'/index'),1);
		$img=new \Think\Verify();
		$result=$img->check(I('code'));
		//if(!$result) $this->error('验证码错误',U(MODULE_NAME.'/'.CONTROLLER_NAME.'/index'),1);
		$db=M('manager');
		$user=$db->where(array('username'=>I('username')))->find();
		if(!$user || $user['password'] != I('password','',md5)){
			$this->error('账号或密码错误',U(MODULE_NAME.'/'.CONTROLLER_NAME.'/index'),1);
		}elseif ($user['status']==0) {
			$this->error('帐号已禁用！',U(MODULE_NAME.'/'.CONTROLLER_NAME.'/index'),1);
		}else{
			$data=array(
				'id'=>$user['id'],
				'logintime'=>time(),
				'loginip'=>get_client_ip(),
				'logincount'=>($user['logincount']+1)
				);
			//更新最后一次登陆时间与ip
			$db->save($data);
			session('uid',$user['id']);
			session('username',$user['username']);
			session('realname',$user['realname']);
			session('logintime',date('Y-m-d H:i',$user['logintime']));
			session('idle', time()+C('SESSION_IDLE'));//登陆时长控制

			//加载仓库权限
			$db=D('ManagerRelation');
			$field=array('id');
			$depot=$db->where(array('id'=>$user['id']))->field($field)->relation('depot')->find();
			foreach ($depot['depot'] as $v) {
				if ($v['del']==0) $depots.=$v['id'].',';
			}
			$depots=rtrim($depots,',');
			session('depots',$depots);
			$this->redirect(MODULE_NAME.'/Index/index');
		}
	}

	//退出登陆
	public function logout(){
		session_unset();
		session_destroy();
		$this->redirect(MODULE_NAME.'/'.CONTROLLER_NAME.'/index');
	}
	//生成验证码
	public function verify(){
		$config=array(
			'useImgBg'  =>  false,           // 使用背景图片 
			'fontSize'  =>  10,              // 验证码字体大小(px)
			'useCurve'  =>  false,            // 是否画混淆曲线
			'useNoise'  =>  false,            // 是否添加杂点	
			'imageH'    =>  24,               // 验证码图片高度
			'imageW'    =>  75,               // 验证码图片宽度
			'length'    =>  4,               // 验证码位数
			'fontttf'   =>  '5.ttf',              // 验证码字体，不设置随机获取
        );
		header("Content-type: image/png");
		$verifyImg=new \Think\Verify($config);
		$verifyImg->entry();
	}
	public function checkVerify(){
		$verifyImg=new \Think\Verify();
		return $verifyImg->check();
	}
    // 更改密码
    public function repwd() {
 		if(!empty($_POST)){
			//修改密码数据
			$img=new \Think\Verify();
			$result=$img->check(I('code'));
			if(!$result) $this->error('验证码错误');

			$map	=	array();
			$map['id']= $_POST['id'];
        	$map['password']= md5($_POST['oldpassword']);
        	$User	 =	 D("manager");
        	if(!$User->where($map)->field('id')->find()) {
            	$this->error('旧密码不符或者用户名错误！');
        	}else {
	            $User->password	=md5($_POST['password']);
	            $User->save();
	            $this->success('密码修改成功！');
         	}
		}else{
			$this->id = $_GET['id'];
			$this->display();
		} 

    }


}